//
//  Categories_iPad_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 12-03-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "Categories_iPhone_ViewController.h"
#import "MyCollectionViewCell.h"
#import "classCategories.h"
#import "dao.h"

@interface Categories_iPhone_ViewController ()

@end

@implementation Categories_iPhone_ViewController

@synthesize dataArrayCategories = _dataArrayCategories;
@synthesize json;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArrayCategories.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCollectionViewCell *myCell = [collectionView
                                    dequeueReusableCellWithReuseIdentifier:@"MyCell"
                                    forIndexPath:indexPath];
    UIImage *image;
//  long row = [indexPath row];
    
    classCategories *objCategories = [_dataArrayCategories objectAtIndex:indexPath.row];
    //  myCell.tag = (long) objCategories.strIdDepartment; //Para no ensuciar la interfaz en vista de diseño utilizo el tag del objeto
    myCell.lblDepartment.text = objCategories.strDepartment;

    NSString *strNameImage = [NSString stringWithFormat:@"%@.jpg", objCategories.strIdDepartment];
    
    //  image = [UIImage imageNamed:_categoryImages[row]];
    image = [UIImage imageNamed:strNameImage];
    
    myCell.imageView.contentMode  = UIViewContentModeScaleToFill;
    myCell.imageView.image = image;
    
    
    NSLog(@"strNameImage =%@", strNameImage);

    NSLog(@"strDepartment =%@", myCell.lblDepartment.text);
    
    
    return myCell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    classCategories *objCategories = [_dataArrayCategories objectAtIndex:indexPath.row];
    
    NSString *strIdDepartment = objCategories.strIdDepartment;
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
    [prefs setObject:strIdDepartment forKey:@"strIdDepartment"]; //Identifica el Id de departamento si la búsqueda es por este concepto

    dao *objDAO = [[dao alloc] init];
    
    [objDAO deleteProductBack];
    [objDAO insertProductBack:2];
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    
    return inputString;
}

- (void) retrieveDataCategories{
    
    [_dataArrayCategories removeAllObjects];
    _dataArrayCategories = [[NSMutableArray alloc] init];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCategoriaProducto.aspx?strJsonBase=JsonDepartamentos"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load Categories perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"id":"2", "desc":"Feretería" }, {"id":"3", "desc":"Gasfitería"}]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<json.count; i++)
             {
                 NSString *strDepartment = [[json objectAtIndex:i] objectForKey:@"desc"];
                 NSString *strCategory = @"";
                 NSString *strSubCategory = @"";
                 NSString *strFamily = @"";
                 
                 NSString *strIdDepartment = [[json objectAtIndex:i] objectForKey:@"id"];
                 NSString *strIdCategory = @"";
                 NSString *strIdSubCategory = @"";
                 NSString *strIdFamily = @"";
                 
                 classCategories *objCategories = [[classCategories alloc] initClassCell:strDepartment andStrCategory:strCategory andStrSubCategory:strSubCategory andStrFamiliy:strFamily andStrIdDepartment:strIdDepartment andStrIdCategory:strIdCategory andStrIdSubCategory:strIdSubCategory andStrIdFamily:strIdFamily];
                 
                 [_dataArrayCategories addObject:objCategories];
             }
             
             [self.collectionView reloadData];
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
}

- (IBAction)callNumber:(id)sender {
    
    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
}

- (IBAction)backCategoriesAction:(id)sender {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    dao *objDAO = [[dao alloc] init];
    
    [objDAO deleteCurrentProduct]; //Limpia la variable para la búsqueda por categorías
    
    [self retrieveDataCategories];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//  [self retrieveDataCategories];
    
    // Do any additional setup after loading the view.
    
    //Cargar las imagenes de categorías en la App directamente
    _categoryImages = [@[@"chevy_small.jpg",
                         @"mini_small.jpg",
                         @"rover_small.jpg",
                         @"smart_small.jpg",
                         @"highlander_small.jpg",
                         @"venza_small.jpg",
                         @"volvo_small.jpg",
                         @"vw_small.jpg",
                         @"ford_small.jpg",
                         @"nissan_small.jpg",
                         @"honda_small.jpg",
                         @"jeep_small.jpg",
                         
                         @"chevy_small1.jpg",
                         @"mini_small1.jpg",
                         @"rover_small1.jpg",
                         @"smart_small1.jpg",
                         @"highlander_small1.jpg",
                         @"venza_small1.jpg",
                         @"volvo_small1.jpg",
                         @"vw_small1.jpg",
                         @"ford_small1.jpg",
                         @"nissan_small1.jpg",
                         @"honda_small1.jpg",
                         @"jeep_small1.jpg",
                         ] mutableCopy];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
